<template>
  <div class="completeBillingPane">
    <section>
      <el-space wrap>
        <div>
          <span class="fs-base">收入</span>
          <span class="fs-large fc-success ml5">￥{{ amountTotalInfo.incomeTotalMoney }}</span>
        </div>
        <div class="ml20">
          <span class="fs-base">支出</span>
          <span class="fs-large fc-danger ml5">￥{{ amountTotalInfo.expensesTotalMoney }}</span>
        </div>
      </el-space>
      <el-button type="primary" plain class="fl-r" @click="handleAddbilling">添加记账</el-button>
    </section>
    <el-table :data="billList" class="mt20" style="width: 100%">
      <el-table-column prop="name" label="费用名称" />
      <el-table-column prop="money" label="金额" />
      <el-table-column prop="payTime" label="日期" :width="100" />
      <el-table-column prop="receiverName" label="操作人" />
      <el-table-column label="图片/备注" :width="80">
        <template #default="scope">
          <el-tooltip
            effect="dark"
            placement="top"
            v-if="scope.row.remark"
          >
            <el-icon class="fs-large mt5" style="cursor: pointer;"><Tickets /></el-icon>
            <template #content>
              <div style="max-width: 200px">{{ scope.row.remark }}</div>
            </template>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="查看图片"
            placement="left"
            v-if="scope.row.picUrl"
          >
            <el-icon  class="fs-large mt5 ml5" style="cursor: pointer;"><Picture /></el-icon>
            <template #content>
              <el-space>
                <el-image style="width: 150px;height: 150px;" :src="item.url" v-for="(item, index) in JSON.parse(scope.row.picUrl)" :key="index" fit="fill" />
              </el-space>
            </template>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" :width="60">
        <template #default="scope">
          <el-dropdown trigger="click" placement="bottom-start" @command="moreCommand($event, scope.row)">
            <el-button link type="primary">更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="editImage">编辑图片</el-dropdown-item>
                <el-dropdown-item command="editRemark">编辑备注</el-dropdown-item>
                <el-dropdown-item command="remove">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      layout="total, prev, pager, next"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 编辑备注信息弹窗 -->
    <BillRemarkDl :visible="remarkVisible" :remark="currentBill.remark" @cancel="handleRemarkClose" @ok="handleRemarkOk"></BillRemarkDl>
    <!-- 编辑图片 -->
    <BillImageUploadDl :visible="imageVisible" :images="picUrlArray" @cancel="handleImageCancel" @ok="handleImageOk"></BillImageUploadDl>
    <!-- 预览图片 -->
    <el-dialog v-model="previewVisible">
      <img w-full :src="previewImageUrl" />
    </el-dialog>
    <!-- 删除账单弹窗 -->
    <BillRemoveDl :visible="removeBillingVisible" :info="currentBill" @cancel="handleRemoveBillingClose" @ok="handleRemoveBillingOk"></BillRemoveDl>
    <!-- 添加记账 -->
    <el-dialog title="添加记账" v-model="addBillingVisible" width="520px" :fullscreen="mobile">
      <el-form :model="addBillingForm" :rules="addBillingRules" ref="addBillingFormRef" label-width="120px">
        <el-form-item prop="inoutFlag" label-width="0">
          <div style="display: flex;justify-content: center;width: 100%;">
            <el-radio-group v-model="addBillingForm.inoutFlag">
              <el-radio label="1">收入</el-radio>
              <el-radio label="2">支出</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="费用名称" prop="name">
          <el-input v-model="addBillingForm.name" placeholder="请输入费用名称"></el-input>
        </el-form-item>
        <el-form-item label="账单金额" prop="money">
          <el-input v-model="addBillingForm.money" placeholder="请输入账单金额"></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="payTime">
          <el-date-picker
            v-model="addBillingForm.payTime"
            type="date"
            placeholder="请选择记账日期"
          />
        </el-form-item>
        <el-form-item label="账单周期" required>
          <el-row>
            <el-col :span="11">
              <el-form-item label-width="0" prop="billCycleBegin">
                <el-date-picker
                  v-model="addBillingForm.billCycleBegin"
                  :editable="false"
                  type="date"
                  placeholder="请选择开始日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div style="text-align: center;">-</div>
            </el-col>
            <el-col :span="11">
              <el-form-item label-width="0" prop="billCycleEnd">
                <el-date-picker
                  v-model="addBillingForm.billCycleEnd"
                  type="date"
                  :editable="false"
                  placeholder="请选择结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addBillingForm.remark" type="textarea" :rows="3" show-word-limit :max="150" placeholder="请填写备注信息"></el-input>
        </el-form-item>
        <el-form-item label="凭证图片" prop="pictureUrlList">
          <el-row>
            <el-col :span="24">
              <div class="fs-base fc-secondary">限3张，图片大小不超过10M</div>
            </el-col>
            <el-col :span="24">
              <el-upload
                v-model:file-list="pictureUrlList"
                action="#"
                list-type="picture-card"
                :http-request="pictureRequestUpload"
                :before-upload="pictureBeforeUpload"
                :multiple="true"
                :limit="3"
                :class="{'is-full': pictureUrlList.length === 3}"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddBillingClose">取消</el-button>
          <el-button type="primary" @click="handleAddBillingOk">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="CompleteBillingPane">
import dayjs from 'dayjs'
import useAppStore from '@/store/modules/app'
import billApi from '@/api/room/bill'
import { onMounted } from 'vue';
import { getToken } from '@/utils/auth'
import BillImageUploadDl from '@/components/BillImageUploadDl/index.vue'
import BillRemarkDl from '@/components/BillRemarkDl/index.vue'
import BillRemoveDl from '@/components/BillRemoveDl/index.vue'

const { proxy } = getCurrentInstance()


const { checkInInfo, updateCheckInInfo } = inject('checkInInfo')
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const headers = ref({ authorization: getToken() })
const remarkVisible = ref(false)
const imageVisible = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const picUrlArray = ref([])
const removeBillingVisible = ref(false)
const addBillingVisible = ref(false)
const pictureUrlList = ref([])
const currentBill = ref({})
const total = ref(0)
const loading = ref(false)
const billList = ref([])
const amountTotalInfo = ref({})
const fileList = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  remarkForm: {
    remark: undefined
  },
  addBillingForm: {
    roomId: undefined,
    inoutFlag: '1',
    checkInId: undefined,
    renterId: undefined, // 租户id
    renterName: undefined, // 租户名称
    // receiverName: undefined, // 收款人姓名
    payPlatForm: '1', // 支付平台（1：线下，2：线上）
    name: undefined, // 账单名称
    money: undefined,
    payTime: dayjs(new Date()).format('YYYY-MM-DD'),
    billCycleBegin: dayjs(new Date()).format('YYYY-MM-DD'), // 账单起始周期
    billCycleEnd: dayjs(new Date()).format('YYYY-MM-DD'), // 账单结束周期
    belong: '1', // 账单类型（1：租客）
    remark: undefined, // 备注
    picUrl: '',
    status: '2', // 账单状态
  },
  addBillingRules: {
    name: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
    money: [
      { required: true, message: "请输入账单金额", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的账单金额", trigger: ["blur", "change"] }
    ],
    payTime: [{ required: true, message: "请选择记账日期", trigger: "blur" }],
    billCycleStart: [{ required: true, message: '请选择账单起始周期', trigger: 'change' }],
    billCycleEnd: [{ required: true, message: '请选择账单结束周期', trigger: 'change' }]
  }
})
const { remarkForm, addBillingForm, addBillingRules, queryParams } = toRefs(data)


// 更多操作按钮
function moreCommand(value, row) {
  currentBill.value = row
  switch (value) {
    case 'editImage':
      handleImage()
      break
    case 'editRemark':
      handleRemark()
      break
    case 'remove':
      handleRemoveBilling()
      break
    default:
      break;
  }
}

// 添加备注弹窗
function handleRemark() {
  remarkVisible.value = true
}
function handleRemarkClose() {
  remarkVisible.value = false
}
function handleRemarkOk() {
  // 判断表单值是否发生改变
  let params = {
    billId: currentBill.value.billId,
    ...value
  }
  billApi.update(params).then(() => {
    proxy.$modal.msgSuccess('备注修改成功')
    remarkVisible.value = false
    getList()
  })
}

// 编辑图片弹窗
function handleImage() {
  picUrlArray.value = currentBill.value.picUrl ? JSON.parse(currentBill.value.picUrl) : []
  imageVisible.value = true
}
function handleImageCancel() {
  imageVisible.value = false
}
function handleImageOk(value) {
  let params = {
    billId: currentBill.value.billId,
    picUrl: value
  }
  billApi.update(params).then(res => {
    proxy.$modal.msgSuccess('图片修改成功')
    imageVisible.value = false
    getList()
  })
}

// 删除账单
function handleRemoveBilling() {
  removeBillingVisible.value = true
}
function handleRemoveBillingClose() {
  removeBillingVisible.value = false
}
function handleRemoveBillingOk(billId) {
  billApi.remove(billId).then(() => {
    proxy.$modal.msgSuccess("账单删除成功");
    removeBillingVisible.value = false
    getList()
  })
}

// 添加账单弹窗
function resetAddBillingForm() {
  addBillingForm.value = {
    inoutFlag: '1',
    name: undefined,
    money: undefined,
    payTime: '',
    remark: undefined,
    pictureUrlList: []
  }
  proxy.resetForm('addBillingFormRef')
}
function handleAddbilling() {
  // resetAddBillingForm()
  addBillingVisible.value = true
}
// 图片上传 覆盖默认上传行为
function pictureRequestUpload() {}
/** 上传预处理 */
function pictureBeforeUpload(file) {
  console.log(file, pictureUrlList.value)
  // if (file.type.indexOf("image/") == -1) {
  //   proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
  // } else {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = () => {
  //     options.img = reader.result;
  //     options.filename = file.name;
  //   };
  // }
}
function handleAddBillingClose() {
  addBillingVisible.value = false
}
function handleAddBillingOk() {
  proxy.$refs['addBillingFormRef'].validate(valid => {
    if (valid) {
      addBillingForm.value.checkInId = checkInInfo.value.checkInId
      addBillingForm.value.roomId = checkInInfo.value.roomId
      let mainRenter = checkInInfo.value.renterList.find(item => item.mainFlag === '1')
      addBillingForm.value.renterId = mainRenter ? mainRenter.renterId : null
      addBillingForm.value.renterName = mainRenter ? mainRenter.name : null
      addBillingForm.value.contacts = mainRenter ? mainRenter.contacts : null
      billApi.save(addBillingForm.value).then(res => {
        addBillingVisible.value = false
        proxy.$modal.msgSuccess('新增成功')
        getList()
      })
    }
  })
}

function getList() {
  loading.value = true
  let params = {
    roomId: checkInInfo.value.roomId,
    ...queryParams.value,
    status: '2'
  }
  billApi.getList(params).then(res => {
    billList.value = res.data.rows
    total.value = res.data.total
    amountTotalInfo.value = res.data
  }).finally(() => {
    loading.value = false
  })
}

onMounted(() => {
  getList()
})
</script>